import React, { useState } from "react";
import axios from "axios";
import { useEffect } from "react";
import "./Duanzi.css";
export default function Duanzi() {
	// 创建状态
	let [duanzi, setDuanzi] = useState([]);
	let [show, setShow] = useState(false);
	let [model, setModel] = useState({});

	//模拟生命周期  componentDidMount
	useEffect(() => {
		async function main() {
			let result = await axios.get("http://api.xiaohigh.com/duanzi");
			console.log(result.data);

			// 提取前20条数据
			let newduanzi = result.data.splice(0, 20);

			//设置数据 状态
			setDuanzi(newduanzi);
		}

		main();
	}, []);

	//切换 弹窗 并设置数据
	let changeshow = (value) => {
		return () => {
			//设置弹窗的段子
			setModel(value);
			//设置 弹窗的显示
			setShow(!show);
		};
	};

	//隐藏 model
	let hide = () => {
		//设置 弹窗的隐藏
		setShow(false);
	};

	return (
		<div className="duanzi">
			<ul>
				{duanzi.map((item) => {
					return (
						<li onClick={changeshow(item)} key={item.id}>
							<h1>
								{item.name.length >= 6
									? item.name.substring(0, 6) + "..."
									: item.name}
							</h1>
							<p>
								{item.text.length >= 100
									? item.text.substring(0, 100) + "..."
									: item.text}
							</p>
						</li>
					);
				})}
			</ul>

			{show ? (
				<div className="bg" onClick={hide}>
					<div className="model">
						<h2>X</h2>
						<h1>{model.name}</h1>
						<p>{model.text}</p>
					</div>
				</div>
			) : (
				""
			)}
		</div>
	);
}
